<?php

class Upload extends Api
{
    public function file()
    {
        $id = $this->getParam('id', '');
        $type = $this->getParam('type', 'image');
        if (!is_numeric($id) || $id <= 0) {
            $this->backJson([], ApiConst::BACK_CODE_ERROR);
        }
        if ($type == 'image') {
            $tempArr = ["image/gif", "image/jpeg", "image/jpg", "image/pjpeg", "image/png", "image/x-png"];
        } else {
            $type = 'document';
            $tempArr = [
                "application/msword",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            ];
        }
        $this->getDb()->where('id', $id);
        $info = $this->getDb()->getOne('infos');
        if (empty($info) || ($info['u_id'] != $this->userInfo['id'] && $info['u_pid'] != $this->userInfo['id'])) {
            $this->backJson([], ApiConst::BACK_CODE_ERROR);
        }
        //$allowedExts = array("gif", "jpeg", "jpg", "png", "doc", "docx", "pdf");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);// 获取文件后缀名
        // $_FILES需要找到对应的文件的MIME 类型，这个可以到网上找
        //["image/gif", "image/jpeg", "image/jpg", "image/pjpeg", "image/x-png"]
        ;
        if (!in_array($_FILES["file"]["type"], $tempArr)) {
            $this->backJson([], 500, "上传的文件格式错误");
        }
        if ($_FILES["file"]["size"] > 10 * 1024 * 1000) {
            $this->backJson([], 500, "上传的文件大小不能超过10Mb");
        }
        if ($_FILES["file"]["error"] > 0) {
            $this->backJson([], 500, $_FILES["file"]["error"]);
        }

        $ymd = date("Ymd");
        $name = time() . "." . $extension;
        $fileName = $ymd . "/" . $name;
        $folder = APP_PATH . "upload/".$type."/" . $ymd . "/"; //上传照片路径
        //开始处理上传
        if (!file_exists($folder))//检查照片目录是否存在
        {
            mkdir($folder, 0777, true);  //mkdir("temp/sub, 0777, true);
        }
        $path = $folder . "/" . $name;//以当前时间和7位随机数作为文件名，这里是上传的完整路径
        move_uploaded_file($_FILES["file"]["tmp_name"], $path);
        $this->getDb()->insert('files', [
            'name' => $fileName,
            'info_id' => $id,
            'type' => $type == 'image' ? 0 : 1,
            'created_at' => time()
        ]);
        $this->backJson([
            'id' => $this->getDb()->getInsertId(),
            'name' => $name,
            'url' => 'http://sbw.shechism.online/api/upload/'.$type.'/' . $fileName
        ]);
    }

    public function info()
    {
        $id = $this->getParam('id');
        if (!is_numeric($id) || $id <= 0) {
            $this->backJson([], ApiConst::BACK_CODE_ERROR);
        }
        $this->getDb()->where('id', $id);
        $info = $this->getDb()->getOne('infos');
        if (empty($info) || ($info['u_id'] != $this->userInfo['id'] && $info['u_pid'] != $this->userInfo['id'])) {
            $this->backJson([], ApiConst::BACK_CODE_ERROR);
        }

        $this->getDb()->where('info_id', $id);
        $files = $this->getDb()->get('files');
        $images = [];
        $documents = [];
        foreach ($files as $file) {
            if ($file['type'] == 0) {
                $images[] = [
                    'id' => $file['id'],
                    'url' => 'http://sbw.shechism.online/api/upload/image/' . $file['name'],
                    'name' => substr($file['name'], strpos($file['name'], '/') + 1)
                ];
            } else {
                $documents[] = [
                    'id' => $file['id'],
                    'url' => 'http://sbw.shechism.online/api/upload/document/' . $file['name'],
                    'name' => substr($file['name'], strpos($file['name'], '/') + 1)
                ];
            }
        }
        $this->backJson(['image' => $images, 'document' => $documents]);
    }

    public function del()
    {
        $id = $this->getParam('id', '');
        if (!is_numeric($id) || $id <= 0) {
            $this->backJson([], ApiConst::BACK_CODE_ERROR);
        }
        $this->getDb()->where('id', $id);
        $file = $this->getDb()->getOne('files');
        if (empty($file)) {
            $this->backJson([], ApiConst::BACK_CODE_ERROR);
        }
        $this->getDb()->where('id', $file['info_id']);
        $info = $this->getDb()->getOne('infos');
        if (empty($info) || ($info['u_id'] != $this->userInfo['id'] && $info['u_pid'] != $this->userInfo['id'])) {
            $this->backJson([], ApiConst::BACK_CODE_ERROR);
        }
        $this->getDb()->where('id', $id);
        $this->getDb()->delete('files');
        if ($file['type'] == 0) {
            $fileName = APP_PATH . "upload/image/" . $file['name'];
        } else {
            $fileName = APP_PATH . "upload/document/" . $file['name'];
        }
        if (file_exists($fileName)) {
            unlink($fileName);
        }
        $this->backJson([]);
    }
}
